package org.alwayssuper.web.endpoint;

import org.alwayssuper.web.model.entity.DeviceDO;
import org.alwayssuper.web.model.enums.SessionKey;
import org.alwayssuper.netmc.core.model.Message;
import org.alwayssuper.netmc.session.Session;
import org.alwayssuper.netmc.session.SessionListener;
import org.alwayssuper.protocol.basics.GBTMessage;
import org.springframework.stereotype.Component;

import java.util.function.BiConsumer;

/**
 * @author alwaysSuper
 */
@Component
public class GBTSessionListener implements SessionListener {

    /**
     * 下行消息拦截器
     */
    private static final BiConsumer<Session, Message> requestInterceptor = (session, message) -> {
        GBTMessage request = (GBTMessage) message;
        request.setClientId(session.getClientId());
        request.setSerialNo(session.nextSerialNo());

        DeviceDO device = session.getAttribute(SessionKey.Device);
        if (device != null) {
            int protocolVersion = device.getProtocolVersion();
            request.setProtocolVersion(protocolVersion);
        }
    };
    @Override
    public void sessionCreated(Session session) {
        session.requestInterceptor(requestInterceptor);
    }

}
